(ns acst.utils.sql-util
  (:use acst.utils.handle-exp)
  (:require [clojure.java.jdbc :as sql]
            [acst.models.db :as db]
            [acst.models.roles :refer [if-is-admin]])
  (:import (java.sql SQLException)))

(defn- without-error-not= [x y]
  (and (not= x y) (nil? (get-error y))))

(defn filter-nil [set-map]
  (reduce-kv  #(if (nil? %3) %1 (assoc %1 %2 %3))
              {} set-map))

(defn find-total-page [table limit]                         ;;此函数不可暴露给外部,有sql注入问题
  (let [{count :count} (first (sql/query db/db [(str "SELECT COUNT(*) FROM " (sql/as-sql-name identity (name table)))]))]
    {:count (int (Math/ceil (/ count limit)))}))

(defn get-talbe-columns [schema, table]
  (sql/query db/db [
                    "SELECT column_name, is_nullable FROM information_schema.columns WHERE table_schema = ? AND table_name = ?"
                    (name schema)  (name table)]))

(defn handle-delete! [user_id table_name user-where-clause admin-where-clause success failed]
  (if
    (or (without-error-not= '(0) (db/delete! table_name user-where-clause))
        (without-error-not= '(0) (if-is-admin user_id (db/delete! table_name admin-where-clause) '(0))))
    success
    failed))

(defn handle-update! [user_id table_name set-map user-where-clause admin-where-clause success failed]
  (if
    (or (without-error-not= '(0) (db/update! table_name set-map user-where-clause))
        (without-error-not= '(0) (if-is-admin user_id (db/update! table_name set-map admin-where-clause) '(0))))
    success
    failed))


